(ns use-fx-clj.abc)

(def c (atom 0))

(def a (take 15 (repeatedly (partial rand-int 100))))

(defn inc! [] (swap! c inc))

(defn find-fn [op]
  (fn do-find [arg]
    (if (> (count arg) 1)
      (loop [rs []
             [x y & rest] arg]
        (cond
          (and x y)
          (do (inc!)
              (if (op x y)
                (recur (conj rs x) rest)
                (recur (conj rs y) rest)))

          x
          (do (inc!)
              (recur (conj rs x) rest))

          :else (do-find rs)))
      (first arg))))

(def find-min (find-fn <))
(def find-max (find-fn >))

(defn calc [arg]
  (loop [smaller []
         bigger []
         [x y & rest] arg]
    (cond
      (and x y)
      (do (inc!)
          (if (< x y)
            (recur (conj smaller x) (conj bigger y) rest)
            (recur (conj smaller y) (conj bigger x) rest)))

      x
      (do (inc!)
          (recur (conj smaller x) (conj bigger x) rest))

      :else [(find-min smaller) (find-max bigger)])))

(println a)
(let [n (count a)]
  (println "n =" (count a))

  (println (calc a))
  (println @c (double (/ @c n)))

  (reset! c 0)
  (println (calc (reverse a)))
  (println @c (double (/ @c n))))
